import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserInfoType } from '@/services/types.ts'
import { clearToken, clearUserInfo, setToken, setUserInfo } from '@/utils/localStorageUtil.ts'

export const useUserStorage = defineStore('userStorage', () => {
  //是否登录
  const isLogin = ref(false)
  // Partial可选的部分属性每个属性都是可选的
  const userInfo = ref<Partial<UserInfoType>>({})

  const currentPath = ref('/')

  //加载本地的用户信息
  let localUserInfo = {}
  try {
    localUserInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  } catch (err) {
    console.log('用户storage里pinia错误 ==>', err)
    localUserInfo = {}
  }
  if (!Object.keys(localUserInfo).length && Object.keys(userInfo.value).length > 0) {
    userInfo.value = localUserInfo
  }

  //主动加载用户信息请求去加载

  const userLoginOut = () => {
    isLogin.value = false
    userInfo.value = {}
    clearToken()
    clearUserInfo()
  }

  const userLoginIn = (user: UserInfoType, token: string) => {
    isLogin.value = true
    userInfo.value = user

    //存token到存用户信息到localStorage
    setToken(token)
    //存用户信息到localStorage
    setUserInfo(user)
  }

  return { isLogin, userInfo, userLoginOut, userLoginIn, currentPath }
})
